﻿using ArticleClientLib;
using eslib.FileManageLib;
using eslib.FormTools;
using HttpServerLib;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using System.Windows.Forms;
using 软文管理;

namespace 软件文管理
{
    public partial class FormNewArticle : Form
    {
        public FormNewArticle()
        {
            new FormSizeAutoChanger(this);
            InitializeComponent();
        }

        void view(string msg)
        {
            Invoke(() =>
            {
                statusView.Text = msg;

                textView.Text += msg + "\r\n";
                if (textView.Text.Length > 2000) textView.Text = textView.Text.Substring(1000);
                textView.Select(textView.Text.Length - 1, 0);
                textView.ScrollToCaret();
            });
        }

        void clearView()
        {
            textView.Text = "";
        }



        AritcleSystem sys;
        ArticleRootDir root => sys.newArticles;

        private void FormNewArticle_Load(object sender, EventArgs e)
        {
            disableUp();
            disableDirAndNew();
            disableOpenArticleDir();

            redirectConsole();

            articleControl1.ClassiflySelectChangeEvent += ArticleControl1_ClassiflySelectChangeEvent;
            articleControl1.ArticleSelectChangeEvent += ArticleControl1_ArticleSelectChangeEvent;

            sys = new AritcleSystem();
            //在控件中显示分类
            articleControl1.UpdateView(root);
        }

        /// <summary>
        /// 软文选择变更
        /// </summary>
        /// <param name="c"></param>
        private void ArticleControl1_ArticleSelectChangeEvent(LocalArticle a)
        {
            CurrentSelectArticle = a;

            labelSelect.Text = $"[当前选择] {a.Article.title}";
            disableUp();

            enableOpenArticleDir($"{a.Article.title}");
        }

        /// <summary>
        /// 分类选择变更
        /// </summary>
        /// <param name="c"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void ArticleControl1_ClassiflySelectChangeEvent(Classifly c)
        {
            CurrentSelectClass = c;
            CurrentSelectArticle = null;

            var json = c.ReadJson();

            labelSelect.Text = $"[当前选择] {json.name}";
            disableUp();
            disableOpenArticleDir();

            enableDirAndNew(json.name);
        }

        Classifly? CurrentSelectClass = null;
        LocalArticle? CurrentSelectArticle = null;




        /// <summary>
        /// 控制台重定向
        /// </summary>
        private void redirectConsole()
        {
            ConsoleTextWriter cwriter = new(view);
            ConsoleRedirector.Redirect(cwriter);
        }

        private void 返回ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            UIDispach.ToStart();
        }



        #region 数据检查
        private void buttonCheck_Click(object sender, EventArgs e)
        {
            clearView();

            //如果选中软文检查软文
            if (CurrentSelectArticle != null)
            {
                checkArticle(CurrentSelectArticle);
                return;
            }

            //选中分类检查下属所有软文
            if (CurrentSelectClass != null)
            {
                checkClass();
            }
        }

        private void checkClass()
        {
            foreach (var a in CurrentSelectClass.Articles)
            {
                checkArticle(a);
            }
            view("分类数据检查结束");
        }

        private void checkArticle(LocalArticle article)
        {
            var (pass, log) = article.Check();
            if (pass)
            {
                view($"[数据检测通过] {article.Article.title}");
                enableUp();
            }
            else
            {
                view($"[数据异常] {article.Article.title}:{log}");
            }
        }
        #endregion


        #region 上传

        void enableUp()
        {
            Invoke(() =>
            {
                buttonUP.Enabled = true;
            });
        }

        void disableUp()
        {
            Invoke(() =>
            {
                buttonUP.Enabled = false;
            });
        }

        private void buttonUP_Click(object sender, EventArgs e)
        {
            clearView();
            disableUp();
            view("软文上传开始");

            //如果选中软文上传软文
            if (CurrentSelectClass != null && CurrentSelectArticle != null)
            {
                _ = upArticle(CurrentSelectClass, CurrentSelectArticle);
                return;
            }

            //选中分类上传下属所有软文
            if (CurrentSelectClass != null)
            {
                _ = upClass(CurrentSelectClass);
                return;
            }
        }

        private async Task upClass(Classifly c)
        {
            var (success, msg) = await sys.UploadNewArticles(c);
            view(msg);
            enableUp();
        }

        private async Task upArticle(Classifly c, LocalArticle a)
        {
            var (success, msg) = await sys.UploadSingleNewArticle(c, a);
            view(msg);
            enableUp();
        }

        #endregion


        #region 打开文件夹与新建软文

        void enableDirAndNew(string name)
        {
            Invoke(() =>
            {
                buttonOpenDir.Text = $"打开文件夹[{name}]";
                buttonOpenDir.Enabled = true;

                buttonNewArticle.Enabled = true;
            });
        }

        void disableDirAndNew()
        {
            Invoke(() =>
            {
                buttonOpenDir.Enabled = false;

                buttonNewArticle.Enabled = false;
            });
        }

        private void buttonOpenDir_Click(object sender, EventArgs e)
        {
            var dir = CurrentSelectClass.Root;

            var fullpath = Path.GetFullPath(dir);
            System.Diagnostics.Process.Start("explorer.exe", fullpath);
        }


        private void buttonNewArticle_Click(object sender, EventArgs e)
        {
            LocalArticle newart = new("./template");
            CurrentSelectClass.AddNew(newart);

            //刷新显示
            articleControl1.UpdateArticle();
        }


        void enableOpenArticleDir(string name)
        {
            Invoke(() =>
            {
                buttonOpenArticleDir.Text = $"打开软文目录[{name}]";
                buttonOpenArticleDir.Enabled = true;

                buttonPreview.Text = $"预览[{name}]";
                buttonPreview.Enabled = true;
            });
        }

        void disableOpenArticleDir()
        {
            Invoke(() =>
            {
                buttonOpenArticleDir.Text = "打开软文目录";
                buttonOpenArticleDir.Enabled = false;

                buttonPreview.Enabled = false;
            });
        }

        private void buttonOpenArticleDir_Click(object sender, EventArgs e)
        {
            var fullpath = Path.GetFullPath(CurrentSelectArticle.Dir);
            System.Diagnostics.Process.Start("explorer.exe", fullpath);
        }



        private void buttonPreview_Click(object sender, EventArgs e)
        {
            ArticleServer.ArticlePreview(CurrentSelectArticle);
        }

        #endregion




        private void 刷新软文列表ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            articleControl1.UpdateArticle();
        }
    }
}
